package com.hiray.viewtouchevent;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import android.widget.ScrollView;

/**
 * Created by hiray on 2018/4/16.
 *
 * @author hiray
 */
public class ScrollViewEx extends ScrollView {
    private static final String TAG = "ScrollViewEx";
    int lastX, lastY;
    boolean isDraging;
    private int touchSlop;

    public ScrollViewEx(Context context) {
        this(context, null);
    }

    public ScrollViewEx(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScrollViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ViewConfiguration configuration = ViewConfiguration.get(context);
        touchSlop = configuration.getScaledTouchSlop();
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.i(TAG, "onInterceptTouchEvent: " + getScrollY() + "---" + computeVerticalScrollRange() + "---" + computeVerticalScrollOffset());
        int action = ev.getAction();
        final ViewParent parent = getParent();
        int scrollHeight = getMeasuredHeight();
        int availableSpace = computeHorizontalScrollRange() - scrollHeight;

        if (action == MotionEvent.ACTION_MOVE && isDraging)
            return true;

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) ev.getX();
                lastY = (int) ev.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                final int y = (int) ev.getY();
                final int yDiff = Math.abs(y - lastY);
                if (yDiff > touchSlop && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) {
                    isDraging = true;
                    lastY = y;
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                }
                //滑动的距离在可以消耗的限度内，拦截，不然不进行拦截
                isDraging = true;
                break;
            case MotionEvent.ACTION_UP:
                isDraging = false;
                break;
        }
        return isDraging;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        return isDraging;
    }
}
